<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\WechatUserModel;
use My\Model\UserRole;

class DistributionShopWechatUserController extends BackgroundController {
	
	private $uid = 0;
    
    public function _initialize() {
    	$this->uid = I("id", 0, "intval");
        $this->setControllerTitle("微信用户管理");
        $this->setActionTitle(array(
            'index' => '微信用户列表',
        	'topological' => '用户发展拓扑',
        	'userTree' => '用户发展树',
        ));
        $this->setActionNav("index");
    }
    
    /**
     * 微信用户列表
     * @param number $is_deleted
     */
    public function getLists( $is_deleted = 0 ) {
    	$type = I('type');
    	$openId = I('openId');
    	$type = $type==''?null:$type;
        $page = $this->getPage ();
        $pagesize = $this->getPageSize ();
        $d = M("WechatUser");
        $condition = array (
            'cid' => $this->aid,
        );
        if ( $openId ) {
        	$condition["openId"] = $openId;
        	$params["openId"] = $openId;
        }
        if ( $type !== null ) {
        	$condition['type'] = array('exp', 'is not null and SUBSTRING(bin(type), -'.($type+1).', 1)*1>0');
        	$params['type'] = $type;
        }
        $nickname = I('nickname', '') and $params['nickname'] = $nickname and $condition['nickname'] = array('like', "%{$nickname}%");
        $wechatUserLists = $d->where ( $condition )->limit ( $pagesize )->page ( $page )->order ( 'id DESC' )->select ();
        $goodsCount = $d->where ( $condition )->count ();
        $userRole = new UserRole();
        foreach ( $wechatUserLists as $k => &$v ) {
        	$v['roles'] = $userRole->type($v['type'])->getUserRoles();
        	$v['showRoles'] = WechatUserModel::getUserTypeName($v['type'], $this->aid, $v['id']);
        	$tree = M("DistributionShopUserTree")->where('uid=%d', $v['id'])->getField('tree');
//         	preg_match('/\d+,(\d+),?/', $tree, $matches);
        	$v['referee'] = M("WechatUser")->where('id=%d', $v['mid'])->field("id,nickname,face,openId")->find();
        }
        $this->assign( 'UserTypesOptions', $this->getOption(WechatUserModel::$USER_TYPES, $type, '==全部==' ));
        $this->assign ( 'wechatUserLists', $wechatUserLists );
        $this->assign ( 'params', $params);
        $this->showPage ( $goodsCount, $pagesize, $params );
        $this->display();
    }
    
    /**
     * 取消金牌会员资格
     */
    public function removeDealerAction() {
        $id = I("id", 0, "intval");
        $m = M("WechatUser");
        $user = $m->where(array("cid"=>$this->aid, "id"=>$id))->find();
        if ( $user ) {
          $userRole = new UserRole();
          if ( $userRole->type($user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
              $userRole->type($user['type'])->clearTo(WechatUserModel::USER_TYPE_FRANCHISED_DEALER);
              $type = $userRole->getType();
              if ( false !== $m->where(array("cid"=>$this->aid, "id"=>$id))->setField("type", $type) ) {
                 false !== M("Dealer")->where("wechat_uid=%d and cid=%d", $id, $this->aid)->setField("is_deleted", 1) and $this->ajaxSuccess("操作成功");
              }
          } else {
              $this->ajaxError("当前用户不是金牌会员");
          }
        }
        $this->ajaxError("操作失败");
    }
    
    /**
     * 用户推广图
     */
    public function topologicalAction() {
    	$this->setLinkNav("用户发展树", __CONTROLLER__."/userTree?id={$this->uid}");
    	$this->setLinkNav("用户发展拓扑", __CONTROLLER__."/topological?id={$this->uid}");
    	$uid = I("id", 0, "intval");
    	$dd = $this->getAcco( $uid, 3 );
    	$this->assign("jsonTree", json_encode($dd[0]));
    	$this->display();
    }
    
    /**
     * 金牌会员信息设置
     */
    public function editInfoAction() {
    	$uid = I("id", 0, "intval");
    	$user = M("WechatUser a")->join("__DEALER__ b on a.id = b.wechat_uid", "LEFT")->where("a.id={$uid}")->field("a.id,a.type,b.id as dealerId")->find();
    	if ( $user ) {
    		$userRole = new UserRole();
    		if ( $userRole->type($user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
    			if ( empty($user['dealerId']) ) {
    				redirect(U('Dealer/add', "wechat_uid={$user['id']}"));
    			}
    			redirect(U("Dealer/modify", "id={$user['dealerId']}"));
    		}
    	}
    	exit("无信息");
    }
    
    /**
     * 金牌会员证书设置
     */
    public function certificateAction() {
    	$uid = I("id", 0, "intval");
    	$user = M("WechatUser a")->join("__DEALER__ b on a.id = b.wechat_uid", "LEFT")->where("a.id={$uid}")->field("a.id,a.type,b.id as dealerId")->find();
    	if ( $user ) {
    		$userRole = new UserRole();
    		if ( $userRole->type($user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
    			if ( empty($user['dealerId']) ) {
    				redirect(U('Dealer/add', "wechat_uid={$user['id']}"));
    			}
    			redirect(U("DistributionShopCertificate/dealerIndex", "id={$user['dealerId']}"));
    		}
    	}
    	exit("无证书");
    }
    
    /**
     * 用户树展示
     */
    public function userTreeAction( ) {
    	$this->setLinkNav("用户发展树", __CONTROLLER__."/userTree?id={$this->uid}");
    	$this->setLinkNav("用户发展拓扑", __CONTROLLER__."/topological?id={$this->uid}");
    	$tree = $this->getAccoTree($this->uid);
    	$this->assign("treeJson", json_encode($tree));
    	$this->display();
    }
    
    /**
     * 获得子树
     */
    public function getSubTreeAction() {
    	//dump($this->getAccoTree($this->uid));
    }
    
    
    private function getAccoTree( $uid, $maxLevel = 3 ) {
    	$i = 0;
    	$m = M("WechatUser");
    	$nodes = $m->where(array('id'=>$uid, 'cid'=>$this->aid))->select();
    	$GLOBALS['maxLevel'] = $maxLevel;
    	$GLOBALS['$users'] = array();
    	function getUser( $nodes, $level ) {
    		global $maxLevel;
    		global $users;
    		if ( $level >= $maxLevel ) {
    		} else {
    			foreach ( $nodes as $v ) {
    				$user = array();
    				$nodeList = M("WechatUser")->where("mid={$v['id']}")->select();
    				$user['id'] = $v['id'];
    				$user['pId'] = $v['mid'];
    				$user['name'] = $v['nickname'];
    				if( $nodeList ) {
    					$user['isParent'] = 1;
    					$subUsers = getUser($nodeList, $level+1);
    				}
    				$users[] = $user;
    				/* foreach ( $subUsers as $v ) { $users[] = $v; } */
    			}
    		}
    		return $users;
    	}
    	return getUser($nodes, 0);
    }
    
    
    private function getAcco( $uid, $maxLevel = 3 ) {
    	$i = 0;
    	$m = M("WechatUser");
    	$nodes = $m->where(array('id'=>$uid, 'cid'=>$this->aid))->select();
    	$GLOBALS['maxLevel'] = $maxLevel;
    	function getUser( $nodes, $level ) {
    		global $maxLevel;
    		$users = array();
    		if ( $level >= $maxLevel ) {
    		} else {
    			foreach ( $nodes as $v ) {
    				$user = array();
    				$nodeList = M("WechatUser")->where("mid={$v['id']}")->select();
    				$user['face'] = $v['face'];
    				$user['key'] = $v['openId'];
    				$user['nickname'] = $v['nickname'];
    				$user['type'] = 'VM';
    				if( $nodeList ) {
    					$user['child'] = 1;
    					$li = getUser($nodeList, $level+1);
    					$li and $user['rel'] = $li;
    				}
    				$users[] = $user;
    			}
    		}
    		return $users;
    	}
    	return getUser($nodes, 0);
    }
}